package net.ideapad.struts.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.ideapad.data.Group;
import net.ideapad.hibernate.HibernateSessionFactory;
import net.ideapad.struts.form.ViewGroupForm;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Session;

/**
 * Action class for displaying the information about a user selected group.
 * 
 * MyEclipse Struts Creation date: 12-13-2009
 * 
 * XDoclet definition:
 * 
 * @struts.action path="/viewGroup" name="viewGroupForm"
 *                input="/form/viewGroup.jsp" scope="request" validate="true"
 */
public class ViewGroupAction extends Action {
	/**
	 * Method to retrieve the information about the group selected by the user.
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
		ViewGroupForm viewGroupForm = (ViewGroupForm) form;
		Integer groupID = viewGroupForm.getGroupID();

		Session session = HibernateSessionFactory.getSession();
		session.beginTransaction();
		
		Group g = (Group) session.createQuery("from Group g where g.groupId = :id").setInteger("id", groupID).uniqueResult();
		
		// Store the group ID.
		request.setAttribute("groupID", groupID);
		request.setAttribute("groupName", g.getGroupName());
		request.getSession().setAttribute("groupID", groupID);

		Integer userID = (Integer) request.getSession().getAttribute("userID");

		// Get the list of groups.
		@SuppressWarnings("unchecked")
		List<Group> groups = session.createQuery("select g from Group g left join fetch g.parentGroup left join fetch g.usersInGroup as ug where g.parentGroup.groupId = :id AND ug.userId = :userID").setInteger("id", groupID).setInteger("userID", userID).list();

		if (groups != null && groups.size() > 0) {
			request.setAttribute("groups", groups);
		}

		session.getTransaction().commit();
		HibernateSessionFactory.closeSession();

		return mapping.findForward("viewGroup");
	}
}